package com.atgm.mall.gmmailmember.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atgm.common.exception.BizCodeEnume;
import com.atgm.common.exception.MemberException;
import com.atgm.common.utils.GmMallUtils;
import com.atgm.common.utils.Query;
import com.atgm.common.utils.R;
import com.atgm.mall.gmmailmember.dao.MemberDao;
import com.atgm.mall.gmmailmember.dao.MemberThumbsArticleDao;
import com.atgm.mall.gmmailmember.entity.MemberEntity;
import com.atgm.mall.gmmailmember.entity.MemberThumbsArticleEntity;
import com.atgm.mall.gmmailmember.feign.ClubFeignService;
import com.atgm.mall.gmmailmember.feign.vo.ArticleFeignVo;
import com.atgm.mall.gmmailmember.service.MemberThumbsArticleService;
import com.atgm.mall.gmmailmember.vo.resp.ArticleThumbsMemberVo;
import com.atgm.mall.gmmailmember.vo.resp.ArticleThumbsRespVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MemberThumbsArticleServiceImpl extends ServiceImpl<MemberThumbsArticleDao, MemberThumbsArticleEntity> implements MemberThumbsArticleService {

    @Autowired
    @Qualifier(value = "clubFeignService")
    private ClubFeignService clubFeignService;

    @Autowired
    private MemberDao memberDao;

    @Override
    public void saveThumbsInfo(Long memberId, Long articleId) {
        //自己无法给自己的文章点赞
        R articleInfoById = clubFeignService.getArticleInfoById(articleId);
        if (0 == articleInfoById.getCode()) {
            ArticleFeignVo data = articleInfoById.getData(new TypeReference<ArticleFeignVo>() {});
            if (data != null) {
                Long selectMemberId = data.getMemberId();
                if (memberId.equals(selectMemberId)) {
                    throw new MemberException("自己无法给自己的文章点赞", BizCodeEnume.MEMBER_THUMBS.getCode());
                }
            }
        }

        //检查该用户是否点赞该文章
        QueryWrapper<MemberThumbsArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("article_id", articleId);
        Integer count = baseMapper.selectCount(queryWrapper);

        if (count == 1) {  //存在，更新则删除
            count = baseMapper.delete(queryWrapper);
            if (count != 1) {
                throw new MemberException("取消点赞失败", BizCodeEnume.MEMBER_THUMBS.getCode());
            }

            //文章点赞数量 -1
            R r = clubFeignService.updateThumbsCount(articleId, 0);
            if (0 != r.getCode()) {
                throw new MemberException("取消点赞失败", BizCodeEnume.MEMBER_THUMBS.getCode());
            }
        }else {  //
            MemberThumbsArticleEntity memberArticleThumbsEntity = new MemberThumbsArticleEntity();
            memberArticleThumbsEntity.setMemberId(memberId);
            memberArticleThumbsEntity.setArticleId(articleId);
            memberArticleThumbsEntity.setCreate_time(new Date());
            memberArticleThumbsEntity.setDeleted(0);
            count = baseMapper.insert(memberArticleThumbsEntity);
            if (count != 1) {
                throw new MemberException("点赞失败", BizCodeEnume.MEMBER_THUMBS.getCode());
            }

            //增加文章的点赞数量
            R r = clubFeignService.updateThumbsCount(articleId, 1);
            if (0 != r.getCode()) {
                throw new MemberException("点赞失败", BizCodeEnume.MEMBER_THUMBS.getCode());
            }
        }
    }

    @Override
    public ArticleThumbsRespVo queryArticleThumbsByArticleId(Long articleId) {
        ArticleThumbsRespVo articleThumbsRespVo = new ArticleThumbsRespVo();
        QueryWrapper<MemberThumbsArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", articleId);

        Page<MemberThumbsArticleEntity> page = new Page<>(1, 5);
        IPage<MemberThumbsArticleEntity> iPage = baseMapper.selectPage(page, queryWrapper);

        List<MemberThumbsArticleEntity> list = iPage.getRecords();
        articleThumbsRespVo.setCount(iPage.getTotal());

        if (GmMallUtils.isEmpty(list)) {
            return articleThumbsRespVo;
        }

        List<Long> selectMemberIdList = list.stream().map(MemberThumbsArticleEntity::getMemberId).collect(Collectors.toList());
        QueryWrapper<MemberEntity> memberEntityQueryWrapper = new QueryWrapper<>();
        memberEntityQueryWrapper.select("id", "header");
        memberEntityQueryWrapper.in("id", selectMemberIdList);
        List<MemberEntity> memberEntities = memberDao.selectList(memberEntityQueryWrapper);

        List<ArticleThumbsMemberVo> articleThumbsMemberVoList = new ArrayList<>();

        list.forEach(memberArticleThumbsEntity -> {
            ArticleThumbsMemberVo articleThumbsMemberVo = new ArticleThumbsMemberVo();
            articleThumbsMemberVo.setId(memberArticleThumbsEntity.getMemberId());
            articleThumbsMemberVo.setHeader(memberEntities.stream().filter(memberEntity -> {
                return memberEntity.getId().equals(memberArticleThumbsEntity.getMemberId());
            }).findAny().get().getHeader());
            articleThumbsMemberVoList.add(articleThumbsMemberVo);
        });

        articleThumbsRespVo.setThumbsList(articleThumbsMemberVoList);

        return articleThumbsRespVo;
    }

    @Override
    public Integer haveThumbsArticle(Long articleId, Long memberId) {
        QueryWrapper<MemberThumbsArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("article_id", articleId);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count;
    }
}
